package com.cloudwave.trailends.ui;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.compo.BaseActivity;
import com.cloudwave.trailends.domain.LinePoint;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.utils.CollectionUtils;
import com.cloudwave.trailends.utils.DateUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

/**
 * 
 * @author DolphinBoy
 * @email dolphinboyo@gmail.com
 * @date 2014-5-6
 * @time 下午10:06:00
 * 
 */

public class PathViewActivity extends BaseActivity {
	private final static String TAG = "PathViewActivity";
	
	private ImageButton btnBack;
//  	private ImageButton btnOK;
  	private TextView tvTitle;
  	
  	private TextView tvTotalMileage;
  	private TextView tvTotalPoint;
  	private TextView tvTotalTime;
  	
  	private ImageButton ibLocate;
  	
//	private LocationMapView mapView;
	private MapView mapView;
	private static BaiduMap baiduMap;
	
//	private SDKReceiver mReceiver;
	
	private DecimalFormat df = new DecimalFormat("#0.00");
	
	
	//考虑重构
	private static Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			@SuppressWarnings("unchecked")
			List<LinePoint> lList = (List<LinePoint>) msg.obj;
			List<LatLng> points = new ArrayList<LatLng>();
			LatLng startPoint = null;
			LatLng endPoint = null;
			int sz = lList.size();
			for (int i=0; i<sz; i++) {
				LinePoint l = lList.get(i);
				LatLng ll = new LatLng(l.getLatitude(), l.getLongitude());
				if (i == 0) {
					startPoint = new LatLng(l.getLatitude(), l.getLongitude());
				}
				if (i == (sz-1)) {
					endPoint = new LatLng(l.getLatitude(), l.getLongitude());
				}
				points.add(ll);
			}
			
			//这里要根据lList.size() 来计算并设置zoom setZoom  ###
			
			//设置线段的颜色，需要传入32位的ARGB格式。默认为黑色( 0xff000000)。
			//http://www.cnblogs.com/Dahaka/archive/2012/03/03/2374799.html
			PolylineOptions options = new PolylineOptions().color(0xFF0070D0).width(10)
					.points(points).zIndex(1);
			baiduMap.addOverlay(options);
			
			BitmapDescriptor startBitmap = BitmapDescriptorFactory  
				    .fromResource(R.drawable.riding_to_start);
			OverlayOptions startOption = new MarkerOptions().position(startPoint)
					.icon(startBitmap).zIndex(2);
			baiduMap.addOverlay(startOption);
			
			BitmapDescriptor endBitmap = BitmapDescriptorFactory  
				    .fromResource(R.drawable.riding_to_end);
			OverlayOptions endOption = new MarkerOptions().position(endPoint)
					.icon(endBitmap).zIndex(2); 
			baiduMap.addOverlay(endOption);
			
			//这里考虑根据路线距离来设定地图等级###
			MapStatusUpdate u1 = MapStatusUpdateFactory.zoomTo(14.0f);
//			baiduMap.animateMapStatus(u1);
			baiduMap.setMapStatus(u1);
			
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(startPoint);
//			baiduMap.animateMapStatus(u);
			baiduMap.setMapStatus(u);
		}
	};
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//注意：在SDK各功能组件使用之前都需要调用, 因此我们建议该方法放在Application的初始化方法中
		//那是否在定位SDK中也用到了呢，如果用到了就要放到Application中###
//		SDKInitializer.initialize(this.getApplicationContext());
		setContentView(R.layout.map_view);
		
		// 注册 SDK 广播监听者
		IntentFilter iFilter = new IntentFilter();
		iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
		iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
//		mReceiver = new SDKReceiver();
//		registerReceiver(mReceiver, iFilter);
				
		initView();
		initMap();
	}
	
	private void initView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
//		btnOK = (ImageButton) findViewById(R.id.btnOK);
		
		tvTotalMileage = (TextView) findViewById(R.id.totalMileage);
		tvTotalTime = (TextView) findViewById(R.id.totalTime);
		tvTotalPoint = (TextView) findViewById(R.id.totalPoint);
		
		ibLocate = (ImageButton) findViewById(R.id.ibLocate);
		
		tvTitle.setText("记录详情");
		ibLocate.setVisibility(View.GONE);
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				PathViewActivity.this.finish();
			}
		});
	}
	
	// 初始化地图
	private void initMap() {
		mapView = (MapView) findViewById(R.id.mapView);
		baiduMap = mapView.getMap();
		mapView.removeViewAt(1);
		
		Long id = getIntent().getLongExtra("rlId", 0);
		if (id == null || id == 0) {
			Toast.makeText(PathViewActivity.this, "参数错误~_~", Toast.LENGTH_SHORT).show();
			Log.w(TAG, "没有接收到参数!");
			return ;
		}
		
		DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
		RidingLine rl = null;
		try {
			rl = dbu.findById(RidingLine.class, id);
		} catch (DbException e) {
			Toast.makeText(PathViewActivity.this, "数据加载失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, "查询记录数据异常:", e);
			return ;
		}
		
		if ( rl == null ) {
			Toast.makeText(PathViewActivity.this, "记录已删除或者丢失~_~", Toast.LENGTH_SHORT).show();
			return ;
		} else {
			String tMStr = getResources().getString(R.string.detail_mileage_holder);  
	        String tMNewStr = String.format(tMStr, df.format(rl.getTotalMileage() / 1000)); 
	        tvTotalMileage.setText(tMNewStr);
			
			String tStr = getResources().getString(R.string.stat_times_en);
			int[] time = DateUtils.duration(rl.getTotalTime() * 1000);
	        String tNewStr = String.format(tStr, time[1], time[2], time[3]);
			tvTotalTime.setText(tNewStr);
			
			tvTotalPoint.setText(String.valueOf(rl.getTotalPoint()));
		}
		
//		List<LinePoint> lList = null;
//		try {
//			 lList = dbu.findAll(Selector.from(LinePoint.class).where("ridingline_id", "==", id).orderBy("createtime_"));
//		} catch (DbException e) {
//			Toast.makeText(PathViewActivity.this, "数据加载失败~_~", Toast.LENGTH_SHORT).show();
//			Log.e(TAG, "查询记录数据异常:", e);
//			return ;
//		}
//		
//		//这里要根据lList.size() 来计算并设置zoom setZoom  ###
//		if (CollectionUtils.isEmpty(lList)) {
//			return ;
//		}
		
		loadLinePoint(dbu, rl.getId());
		
//		List<LatLng> points = new ArrayList<LatLng>();
//		LatLng startPoint = null;
//		LatLng endPoint = null;
//		int sz = lList.size();
//		for (int i=0; i<sz; i++) {
//			LinePoint l = lList.get(i);
//			LatLng ll = new LatLng(l.getLatitude(), l.getLongitude());
//			if (i == 0) {
//				startPoint = new LatLng(l.getLatitude(), l.getLongitude());
//			}
//			if (i == (sz-1)) {
//				endPoint = new LatLng(l.getLatitude(), l.getLongitude());
//			}
//			points.add(ll);
//		}
//		
//		//设置线段的颜色，需要传入32位的ARGB格式。默认为黑色( 0xff000000)。
//		//http://www.cnblogs.com/Dahaka/archive/2012/03/03/2374799.html
//		PolylineOptions options = new PolylineOptions().color(0xFF0070D0).width(10)
//				.points(points).zIndex(1);
//		baiduMap.addOverlay(options);
//		
//		BitmapDescriptor startBitmap = BitmapDescriptorFactory  
//			    .fromResource(R.drawable.riding_to_start);
//		OverlayOptions startOption = new MarkerOptions().position(startPoint)
//				.icon(startBitmap).zIndex(2);
//		baiduMap.addOverlay(startOption);
//		
//		BitmapDescriptor endBitmap = BitmapDescriptorFactory  
//			    .fromResource(R.drawable.riding_to_end);
//		OverlayOptions endOption = new MarkerOptions().position(endPoint)
//				.icon(endBitmap).zIndex(2); 
//		baiduMap.addOverlay(endOption);
//		
//		//这里考虑根据路线距离来设定地图等级###
//		MapStatusUpdate u1 = MapStatusUpdateFactory.zoomTo(14.0f);
////		baiduMap.animateMapStatus(u1);
//		baiduMap.setMapStatus(u1);
//		
//		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(startPoint);
////		baiduMap.animateMapStatus(u);
//		baiduMap.setMapStatus(u);
	}
	
	private void loadLinePoint(final DbUtils dbu, final Long id) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				Message msg = handler.obtainMessage();
				List<LinePoint> lList = null;
				try {
//					 DbUtils dbu = DbUtils.create(PathViewActivity.this, Constants.DB_NAME);
					 lList = dbu.findAll(Selector.from(LinePoint.class).where("ridingline_id", "==", id).orderBy("createtime_"));
				} catch (DbException e) {
					Toast.makeText(PathViewActivity.this, "数据加载失败~_~", Toast.LENGTH_SHORT).show();
					Log.e(TAG, "查询记录数据异常:", e);
					return ;
				}
				msg.obj = lList;
				if (CollectionUtils.isEmpty(lList)) {
					return ;
				}
				handler.sendMessage(msg);
			}
		}).start();
	}
	
	/**
	 * 构造广播监听类，监听 SDK key 验证以及网络异常广播
	 */
//	public class SDKReceiver extends BroadcastReceiver {
//		public void onReceive(Context context, Intent intent) {
//			String s = intent.getAction();
//			Log.d(TAG, "action: " + s);
//			if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
//				//Toast.makeText(PathViewActivity.this, "地图KEY验证出错，请反馈给我们！", Toast.LENGTH_SHORT).show();
//				Log.v(TAG, "地图KEY验证出错！");
//			} else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
//				//Toast.makeText(PathViewActivity.this, "网络出错！", Toast.LENGTH_SHORT).show();
//				Log.v(TAG, "网络出错！");
//			}
//		}
//	}
	
	@Override
	protected void onResume() {
		mapView.onResume();
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		mapView.onPause();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (mapView != null) {
			mapView.onDestroy();
			mapView = null;
		}
		super.onDestroy();
//		unregisterReceiver(mReceiver);
	}
	
}
